<?php

class servletAction extends BaseAction {

    public function  execute() {
        $this->uhash    = $this->params['uhash'];
        $this->key    = $this->params['app_key'];
        $this->auth     = 0;
        if(!array_key_exists('user', $_SESSION)){
            $this->uid    = 0;
        }else{
            $this->uid    = $_SESSION['user']['id'];
        }
        if(empty($this->uhash) && $this->auth) {
            $key    = $this->getAppKey();
            if(!in_array($this->key, $key)) {
                echo 'app_key error please refresh page!';
                exit;
            }
        }
        $this->view->layout = '';
        parent::execute();
    }

    /**
     * 返回验证码
     * @return <type>
     */
    public function getAppKey(){
        $key_mid    = strtotime(date('Y-m-d H:00:00'));
        $key_pre    = $key_mid - 3600;
        $key_las    = $key_mid + 3600;
        return array(md5($key_mid), md5($key_las), md5($key_pre));
    }
    /**
     * 月统计
     */
    public function actionMonthCount() {
        $uhash  = $this->params['uhash'];
        if(empty($uhash)) {
            echo '暂时没有统计数据';
            exit;
        }

        $ip_key = 'month_count_ip_'.$uhash;
        $pv_key = 'month_count_pv_'.$uhash;
        $y1_key = 'month_count_day_'.$uhash;
        $mem    = MemcacheAction::getCache();

        $ip     = $mem->get($ip_key);
        $pv     = $mem->get($pv_key);
        $y1     = $mem->get($y1_key);

        if(!$ip){
            
            load_help('DateTime');
            $id = $this->params['id'];
            $time_stamp = 3600*24 *10;
            $hour   = getMonthCount($time_stamp, '-');
            asort($hour);
            //获取pv
            foreach ($hour as $k=>$v):
                $y1[]   =  date('d',$v['start']);
                $pv[]   = DB_ACCESS::getPv($uhash, $v['start'], $v['end']);
                $ip[]   = DB_IP::getIp($uhash, $v['start'], $v['end']);
                //echo date('Y-m-d H:i:s',$v['start']).'--'.date('Y-m-d H:i:s',$v['end']).'<br/>';
            endforeach;
            $life    = 3600*24*3;
            $mem->set($ip_key, $ip, $life);
            $mem->set($pv_key, $pv, $life);
            $mem->set($y1_key, $y1, $life);
        }
        $this->set('ip',  '['.implode(',', $ip).']');
        $this->set('pv',  '['.implode(',', $pv).']');
        $this->set('y1',  '['.implode(',', $y1).']');
        $this->render('hour_count');
    }
    /**
     *日统计
     */
    public function actionHourCount() {
        $uhash  = $this->params['uhash'];
        if(empty($uhash)) {
            echo '暂时没有统计数据';
            exit;
        }

        $ip_key = 'hour_count_ip_'.$uhash;
        $pv_key = 'hour_count_pv_'.$uhash;
        $y1_key = 'hour_count_day_'.$uhash;
        $mem    = MemcacheAction::getCache();

        $ip     = $mem->get($ip_key);
        $pv     = $mem->get($pv_key);
        $y1     = $mem->get($y1_key);

        
        $this->view->layout = '';
        $pv = array();
        $ip = array();
        if(!$ip){
            load_help('DateTime');
            $hour   = getHourCount(3600*5,'-',12);
            asort($hour);
            //获取pv
            foreach ($hour as $k=>$v):
                $date   = date('G',$v['start']);
                if ($date==0) {
                    $date   = 24;
                }
                $y1[]   =  $date;
                $pv[]   = DB_ACCESS::getPv($uhash, $v['start'], $v['end']);
                $ip[]   = DB_IP::getIp($uhash, $v['start'], $v['end']);
            endforeach;
        }
        $this->set('ip',  '['.implode(',', $ip).']');
        $this->set('pv',  '['.implode(',', $pv).']');
        $this->set('y1',  '['.implode(',', $y1).']');
        $this->render();
    }

    /**
     * 来路统计
     */
    public function actionRefererCount() {
        $uhash  = $this->params['uhash'];
        if(empty($uhash)) {
            echo '暂无数据';
            exit;
        }
        
        $key    = 'referer_count'.$uhash;
        $mem    = MemcacheAction::getCache();
        $rs     = $mem->get($key);
        if(!$rs) {
            $this->view->layout = '';
            $sql    = "SELECT * , count( id ) AS count FROM `u22_access` WHERE uhash='$uhash' GROUP BY referer order by id desc limit 0,10 ";
            $rs = DAO_Finder::result($sql);
            if(empty($rs)) {
                echo '暂无数据';
                exit;
            }
            $mem->set($key, $rs,3600);
        }

        $this->set('rs', $rs);
        $this->render();
    }
    
    /**
     * 操作系统统计
     */
    public function actionOsCount() {

        $uhash  = $this->params['uhash'];
        $key    = 'os_'.$uhash;
        $mem  = MemcacheAction::getCache();
        $arr    = $mem->get($key);
        if(!$arr) {
            $rs     = DAO_Finder::find(DB_URL_OS, array('uhash'=>$uhash), 'name,click');

            $arr    = array();
            if(!$rs){
                echo '暂无统计信息';
                exit;
            }
            foreach ($rs as $k => $v):
                $v  = $v->getArray();
                if(empty($v['name'])) {
                    $v['name']   =0;
                }
                if(empty($v['click'])) {
                    $v['click']   =0;
                }
                $arr[]    = "['".$v['name']."',".$v['click']."]";
            endforeach;
            $mem->set($key, $arr,3600);
        }
        $this->set('show', implode(',', $arr));
        $this->render();
    }

    /**
     * 浏览器统计
     */
    public function actionIeCount() {
        $uhash  = $this->params['uhash'];
        $key    = 'ie_'.$uhash;
        $mem  = MemcacheAction::getCache();
        $arr    = $mem->get($key);
        if(!$arr) {
            $rs     = DAO_Finder::find(DB_URL_IE, array('uhash'=>$uhash), 'name,click');

            $arr    = array();
            if(!$rs){
                echo '暂无统计信息';
                exit;
            }
            foreach ($rs as $k => $v):
                $v  = $v->getArray();
                if(empty($v['name'])) {
                    $v['name']   =0;
                }
                if(empty($v['click'])) {
                    $v['click']   =0;
                }
                $arr[]    = "['".$v['name']."',".$v['click']."]";
            endforeach;
            $mem->set($key, $arr,3600);
        }
        $this->set('show', implode(',', $arr));
        $this->render();
    }

    public function actionProvinceCount() {
        $uhash  = $this->params['uhash'];
        $key    = 'province_'.$uhash;
        $mem  = MemcacheAction::getCache();
        $rs   = $mem->get($key);
        if(!$rs) {
            $rs = DAO_Finder::find(DB_URL_PROVINCE, array('uhash' =>$uhash));
            if(!$rs){
                echo '暂无统计信息';
                exit;
            }
            $mem->set($key, $rs ,  3600);
        }

        $this->set('rs', $rs);
        $this->render();
    }
    
    public function actionSpiderCount() {
        $uhash  = $this->params['uhash'];
        $key    = 'spider_'.$uhash;
        $mem  = MemcacheAction::getCache();
        $rs   = $mem->get($key);
        if(!$rs) {
            $rs = DAO_Finder::find(DB_URL_SPIDER, array('uhash' =>$uhash));
            if(!$rs){
                echo '暂无统计信息';
                exit;
            }
            $mem->set($key, $rs ,  3600);
        }

        $this->set('rs', $rs);
        $this->render('province_count');
    }

    /**
     * 添加短网址
     */
    public function actionAddUrl() {
        $last_add   = $_SESSION['add_time'];

        if((time()-$last_add)<10) {
            echo json_encode(array('code'=>'error','msg'=>'添加频率过快','url'=>base64_encode($url)));
        }
        $url    = $this->postVar('url');
        $custom = $this->postVar('custom');
        $guest  = $this->postVar('guest');
        $return = array();
        if(!array_key_exists('user', $_SESSION)){
            $uid    = 0;
        }else{
            $uid    = $_SESSION['user']['id'];
        }

        if($url) {
            //获取腾讯短网址
            get_block('home', 'get_tencent_url',array('url'=>$url));
            $return['tencent'] = $_SESSION['tencent_url'];
            if(!array_key_exists('tencent_url', $_SESSION)){
                echo json_encode(array('code'=>'error','msg'=>'已存在该腾讯短网址','url'=>base64_encode($url)));
                exit;
            }

            //获取新浪短网址
            $baseUrl = 'http://'.$_SERVER['HTTP_HOST'].'/cgi/sina/short_url.php?q=' . base64_encode($url);

            $return['sina'] =  trim(file_get_contents($baseUrl));

            $_SESSION['sina_url']   = $return['sina'];
            
            if(strlen($return['sina']) != 6 ){
                echo json_encode(array('code'=>'error','msg'=>'已存在该新浪短网址','url'=>base64_encode($url)));
                exit;
            }elseif(strlen($_SESSION['tencent_url']) !=6){
                 echo json_encode(array('code'=>'error','msg'=>'已存在该腾讯短网址','url'=>base64_encode($url)));
                 exit;
            }
            //保存信息
            $save   = DB_URL::add($url,0, $uid);
            //保存自定义后缀
            if(array_key_exists('user', $_SESSION)){
                if($_SESSION['user']['is_custom'] ||$custom) {
                    $has    = DB_URL::checkUhash($uhash);
                    if(!$has){
                        $save->setUhash($custom);
                        $save   = $save->save();
                    }
                }
            }
            $return['u22']  = $save->getUhash();
            $return['code'] = 'ok';

            //访客选项
            if(!$this->uid){
                $_SESSION['uhash']    = $return['u22'];
                $this->actionGuestUrlAdd();
            }

            //清除会员url
            if(!$guest) {
                unset($_SESSION['cache']['my_url_list']);
            }
            $_SESSION['add_time']   = time();
            echo json_encode($return);
            exit;
        }else{
            echo json_encode(array('code'=>'error','msg'=>'添加失败','act' =>1));
            exit;
        }
        echo json_encode(array('code'=>'error','msg'=>'非法参数','act' =>1));
    }
    /**
     * 未登陆停止;
     */
    private function checkLogin() {
        if(empty($_SESSION['user'])){
            exit;
        }
    }

    /**
     * 我的短网址
     */
    public function actionMyUrlList(){
        if(!array_key_exists('my_url_list', $_SESSION['cache'])) {
            $uid    = $_SESSION['user']['id'];
            $rs     = DAO_Finder::find(DB_URL, array('uid'=>$uid), 'id,uid,uhash,sina_url,tencent_url,title,total_pv,total_ip,url','id desc', '0,10');
            //print_r($rs);
            $arr    = array();
            if($rs) {
                $log_time   = date('Ymd');
                foreach ($rs as $k => $v) {
                    $uhash  = $v->getUhash();
                    $ip    = DAO_Finder::findOne(DB_COUNT_IP, array('uhash'=>$uhash), 'log_time', 'id desc');
                    $pv    = DAO_Finder::findOne(DB_COUNT_PV, array('uhash'=>$uhash), 'log_time', 'id desc');
                    $tmp    = $v->getArray();
                    if(strlen($tmp['url']) > 50) {
                        $tmp['url'] = substr($tmp['url'], 0, 50);
                    }
                    

                    //获取今日ip
                    if(!$ip){
                        $tmp['ip']  = 0;
                    }else{
                        $tmp['ip'] = $ip->getLogTime();
                    }

                    //获取pv
                    if(!$pv){
                        $tmp['pv']  = 0;
                    }else{
                        $tmp['pv'] = $pv->getLogTime();
                    }
                    $arr[]  = $tmp;
                    unset($tmp);
                }
                $_SESSION['cache']['my_url_list']    = $arr;
            }else{
                echo json_encode(array('code' => 'ok', 'msg' => '您还没有添加短网址'));
                exit;
            } 
        }
        echo json_encode(array('code' => 'ok', 'data' => $_SESSION['cache']['my_url_list']));
    }

    //游客添加短
    function actionGuestUrlAdd() {
        $uhash  = $_SESSION['uhash'];
        //不存在
        if(!$uhash) {
            exit;
        }

        if(array_key_exists('guest_url', $_SESSION)) {
            $url    = $_SESSION['guest_url'];
        }else{
            $url    = array();
        }
        
        $rs = DAO_Finder::findOne(DB_URL, array('uhash' => $uhash));
        //没记录;
        if(!$rs) {
            exit;
        }
        $tmp    = $rs->getArray();
        //获取今日ip
        $ip = DAO_Finder::findOne(DB_COUNT_IP, array('uhash'=>$uhash), 'log_time', 'id desc');
        if(!$ip){
            $tmp['ip']  = 0;
        }else{
            $tmp['ip']  = $ip->getIp();
        }
        //获取今日pv
        $pv = DAO_Finder::findOne(DB_COUNT_PV, array('uhash'=>$uhash), 'log_time', 'id desc');
        if(!$pv){
            $tmp['pv']  = 0;
        }else{
            $tmp['pv']  = $ip->getPv();
        }
        $_SESSION['guest_url'][]   = $tmp;
        Cookies::setMine($uhash);
        unset($_SESSION['uhash']);
    }

    public function actionGuestUrlList() {
        $this->set('rs', $_SESSION['guest_url']);
        $this->render();
    }
    /**
     * 我的短网址数量
     */
    public function actionTotalUrl(){
        $total  = DAO_Finder::findCount(DB_USER, array('uid' => $_SESSION['user']['id']));
        echo $total;
    }
}

